<template>
  <view class="safe-area-inset-bottom">
    <!-- 顶部导航 -->
    <uni-nav-bar :fixed="true" backgroundColor="#00a660" color="#fff" height="90rpx">
      <block slot="left">
        <i class="iconfont nav_backIcon" @click="back">&#xe8b8;</i>
        <span style="font-size: 30rpx;">文件内容填写</span>
      </block>
      <block slot="right">
        <view class="nav_btn">
          <button @click="save" class="backBtn" size="mini">保存草稿</button>
          <button @click="next" class="nextBtn" size="mini">下一步</button>
        </view>
      </block>
    </uni-nav-bar>
    <!-- 合同内容显示 -->
    <uni-data-select v-model="selectFileId" :localdata="contractFilename" :clear="false" class="data_select"></uni-data-select>
	<view class="agree_jn">
		<view class="contact-content" ref="myView" v-for="(item,index) in contractFile" v-show="selectFileId==item.id" v-html="item.htmlPath" :style="{width:widthNum + 'px'}"
		      @input="addComment"></view>
	</view>	  
	<uni-fab ref="fab" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
		style="opacity: 0.9;" :direction="direction" @trigger="changeSize" :icon="search" />
    <!-- 参数设置 -->
    <view class="add_content">
      <span>共有 {{ contractTemplateParamAllNumber}} 个填写参数，已填写 {{ parameterSize }} 个。</span>
    </view>
  </view>
</template>

<script>
import config from '@/config'
import {getContract, updateContractNext} from "@/api/ec/work/contract/contract";
import {html2pdfProgress} from "@/api/ec/work/contract/contractFile";
import {selectContractFileListAddContentByContractId, templateSaveDraft} from "@/api/ec/work/contract/contractFile";

export default {
  data() {
    return {
	  search: 'search',
	  content: [{ 
	  		text: '放大',
	  		active: false
	  	},
	  	{
	  		text: '缩小',
	  		active: false
	  	},
	  ],
	  widthNum: '',
      parameterSize: 0, //填写的参数个数
      parameterSizeSet: new Set(), //填写的参数个数临时辅助数据 
      location: 'location',
      contractId: '',
      idx: 0,//选中索引
      selectFileId: '', //切换文件
      host: config.baseUrl,
     directionStr: '垂直',
     horizontal: 'right',
     vertical: 'bottom',
     direction: 'vertical',
     pattern: {
     	color: '#3c3e49',
     	backgroundColor: '#fff',
     	selectedColor: '#00a660',
     	buttonColor: '#00a660',
     	iconColor: '#fff'
     },
      contentHtml: '', // html
      contractFile: [], // 合同附件
      contractFilename: [], //切换合同
      contractTemplateParamAllNumber: 0,// 全部参数个数
      ruleForm: [],// 合同信息
      contractTempParam:new Map(),//临时参数保存
    };
  },
  onLoad(option) {
    this.contractId = option.id
    // 初始 合同信息
    this.initContractData();
    // 初始 合同文件
    this.initContractFile();
    // 监听post子页面消息
    setTimeout(() =>{
     this.saveTempData();
    },1000)
  },
  onUnload() {
  },
  methods: {
	/** 放大缩小 */
	changeSize(e) {
		// 放大
		if (e.index == 0) {
			let dragWidth = document.getElementsByClassName("contact-content")[0].clientWidth
			this.widthNum = dragWidth + 50
		} else if(e.index == 1){
			// 缩小
			let dragWidth = document.getElementsByClassName("contact-content")[0].clientWidth
			if (dragWidth > document.getElementsByClassName('agree_jn')[0].clientWidth) {
				this.widthNum = dragWidth - 50
			}
		}
	},
    // 回调已经填写的参数个数 h5
    handelMessage(e) {
      // 已经填写 排除其他消息
      if(!!e.data.data){
        this.parameterSize = e.data.data.arg.okNumber;
      }
    },
    // 回调已经填写的参数个数 小程序 app
    message(e){
      this.parameterSize = e.data.data.arg.okNumber;
    },
    /** 初始化合同文件 */
    initContractData() {
      this.flowId = this.$mp.query.flowId;
      if (!this.contractId) {
        return;
      }
      // 初始合同信息
      getContract(this.contractId).then((response) => {
        this.ruleForm = response.data;
      });
    },
    initContractFile() {
      // 地址栏参数
      let contractId = this.$route.query.id;
      selectContractFileListAddContentByContractId(contractId).then((response) => {
        this.contractFile = [];
        for (let i = 0; i < response.data.length; i++) {
          let file = response.data[i]
          if (file.fileType == 0) {
            this.contractFilename.push({value: file.id, text: file.name});
            this.selectFileId = this.contractFilename[0].value;//默认选中
            // 加载文件参数
            file.contractTemplateParam.forEach(data => {
              // 赋值全部参数个数
              this.contractTemplateParamAllNumber++;
              if (data.paramValue != null && data.paramValue != "") {
                file.paramNum += 1;
              }
            })
            // 标签可编辑
            file.htmlPath= file.htmlPath.replace(/contenteditable=\"false\"/g, "contenteditable=\"true\"")
            this.contractFile.push(file);
          }
        }
      });
    },
    // 记录输入事件
    addComment() {
      // 根据参数列表查询dom树
      this.contractFile.forEach(file => {
        // 查询所有参数
        file.contractTemplateParam.forEach(fileParam => {
          let innerText = document.getElementById(fileParam.ids).innerText;
          // 改变过的数据则进行记录
          if (innerText != this.contractTempParam.get(fileParam.ids)) {
            // 已经填写的数据
            this.parameterSizeSet.add(fileParam.ids);
          }
        })
      })
      this.parameterSize = this.parameterSizeSet.size;
    },
    // 保存临时数据 为数据比对修改了哪个输入框做准备
    saveTempData(){
      this.contractFile.forEach(file => {
        // 查询所有参数
        file.contractTemplateParam.forEach(fileParam => {
          let innerText = document.getElementById(fileParam.ids).innerText;
          // 保存临时数据
          this.contractTempParam.set(fileParam.ids,innerText);
        })
      })
    },
    /** 保留草稿 */
    save() {
      this.$modal.loading("保存中，请稍候...");
      let data = {}
      data.contractId = this.ruleForm.id;
      data.contractNumber = this.ruleForm.contractNumber;
      data.innerHTML = [];// 全部文件的html
      for (let i = 0; i < this.contractFile.length; i++) {
        data.innerHTML.push(document.getElementsByClassName('contact-content').item(i).innerHTML);
      }
      templateSaveDraft(data).then(response => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess("保存成功！");
        uni.switchTab({url: '/pages/index'})
      });
    },
    /** 返回 */
    back() {
      uni.navigateBack({
        delta: 1,
      })
    },
    /**下一步 */
    next() {
      // 检验模板参数值是否填写
      if (this.contractTemplateParamAllNumber != this.parameterSize) {
        this.$modal.msgError("请填写模板参数！")
        return;
      }
      // 设置 文件待签章签名
      this.ruleForm.status = 3;
      updateContractNext(this.ruleForm).then(response => {
        this.$modal.loading("转换中，请稍候...");
        // // 填写html 并生成pdf
        let data = {}
        data.contractId = this.ruleForm.id;
        data.contractNumber = this.ruleForm.contractNumber;
        data.innerHTML = [];// 全部文件的html
        for (let i = 0; i < this.contractFile.length; i++) {
          data.innerHTML.push(document.getElementsByClassName('contact-content').item(i).innerHTML);
        }
        html2pdfProgress(data).then((response) => {
          this.$modal.closeLoading()
          uni.navigateTo({url: '/pages/sign/upSign?id=' + this.ruleForm.id})
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
	.agree_jn {
		background-color: #fff;
		margin: 230rpx 0 100rpx;
		width: 100%;
		overflow-y: scroll;
	}
	::v-deep .uni-fab__circle--rightBottom {
		bottom: 200rpx;
		right: 50rpx;
		z-index: 0;
	}

	::v-deep .uni-fab--rightBottom {
		bottom: 200rpx;
		right: 50rpx;
		z-index: 0;
	}

.nextBtn {
  background: $uni-color-primary;
  color: #fff;
  border: solid 1rpx #fff;
  height: 55rpx;
  line-height: 55rpx;
  margin-left: 20rpx;
}

::v-deep .uni-navbar__header-btns-left {
  width: 220rpx !important;
}

::v-deep .uni-navbar__header-btns-right {
  width: 420rpx !important;
}

.add_content {
  background: $uni-color-primary;
  color: #fff;
  height: 70rpx;
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 0 30rpx;
  align-items: center;
  position: fixed;
  bottom: 0;
  bottom: constant(safe-area-inset-bottom);
  bottom: env(safe-area-inset-bottom);

  .iconfont {
    font-weight: bold;
  }
}


::v-deep .uni-data-checklist .checklist-group .checklist-box {
  margin-right: 50rpx;
}

.uni-data-checklist .checklist-group .checklist-box {
  margin: 6rpx 0;
}

page {
  background: $uni-bg-color;
}

.contact-content {
  margin: 0 auto;
  padding: 0 30rpx;
  // padding: 130rpx 30rpx 80rpx 0;
  position: relative;
}
</style>
